﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TypeWrite.Core;
using TypeWrite.Data;
using TypeWrite.MVC4.Areas.Setup.Models;
using TypeWrite.MVC4.Filters;
using WebMatrix.WebData;

namespace TypeWrite.MVC4.Areas.Setup.Controllers
{
    [InitializeSimpleMembership]
    public class AdminAccountController : Controller
    {
        TypeWriteDataContext db = ContextFactory.CreateInstance(string.Empty);

        //
        // GET: /Setup/AdminAccount/Default

        public ActionResult Create()
        {
            if (!db.webpages_Roles.Any(r => r.RoleName == Roles.AdminRoleName))
            {
                db.webpages_Roles.InsertOnSubmit(new webpages_Role { RoleName = Roles.AdminRoleName });
                db.SubmitChanges();
            }

            return View(new AdminAccount());
        }

        //
        // POST: /Setup/AdminAccount/Default
        [HttpPost]
        public ActionResult Create(AdminAccount model)
        {
            try
            {

                WebSecurity.CreateUserAndAccount(model.Username, model.Password);

                Data.User user = db.Users.SingleOrDefault(u => u.Username == model.Username);

                webpages_Role role = db.webpages_Roles.FirstOrDefault(r => r.RoleName == Roles.AdminRoleName);

                db.webpages_UsersInRoles.InsertOnSubmit(new webpages_UsersInRole { RoleId = role.RoleId, UserId = user.UserId });

                db.SubmitChanges();

                if (WebSecurity.Login(model.Username, model.Password))
                {
                    return RedirectToAction("Settings", "Install", new { area = "Setup" });
                }
                else
                {
                    return View("Error", new HandleErrorInfo(new Exception("Could not log in to Admin account"), "AdminAccount", "Create"));
                }
            }
            catch (Exception ex)
            {
                return View("Error", new HandleErrorInfo(ex, "AdminAccount", "Create"));
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            db.Dispose();
        }

    }
}
